package com.fx.controller;

import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

import com.check.Check_Info;
import com.dto.cnc.CncDTO;
import com.dto.config.IniDTO;
import com.safe.CheckCNCImpl;
import com.sftpserver.RunServer;
import com.sftpserver.TestService;
import com.utils.*;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.ComponentScan;
import com.fx.jfxsupport.FXMLController;
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import static com.fx.notify.NotifyTest.doNotify;

//@EnableScheduling/*定时器*/
@Slf4j(topic = "页面核心控制类")
@FXMLController
@ComponentScan({"com"})/*搜索路径*/
public class ApplicationController/* extends MobileApplication*/
        implements Initializable,Consumer<Stage>,SchedulingConfigurer
{

    @FXML
    public Button btn_record;
    @FXML
    public Pane main_ui;

    /*SFTP信息*/
    @FXML
    public TextField sftp_server_uri;
    @FXML
    public TextField sftp_server_user;
    @FXML
    public TextField sftp_server_pwd;

    public TextField sftp_server_path;

    public TextField sftp_server_port;

    /*opc用户名密码*/
    public TextField username_info;
    public TextField password_info;
    public TextField ip_info;
    public TextField port_Info;
    /*opc密钥路径*/

    public TextField key_path_info;
    /*opc服务地址*/
    public TextField opcserver_path;
    /*opc服务节点*/
    public TextField server_id;

 /*机床IP地址*/
    public TextField cnc_net_ip;
    /*机床socket通讯端口*/
    public TextField cnc_net_port;


    public TextField cncworkmode;


    public Button checkOnline;

//    @FXML
//    public TextField listen_info;

    public ToggleButton sftp_button;

    public ToggleButton opc_button;

    public TextField opc_server_uri;

    public Button btn_exit;

    public ToggleButton listenCNC;

    public Label disk_check;

    public Label num_count;


    public TextField shou_quan;
    public TextField api_url;

    public void checkOnline(ActionEvent event) {
        this.a();
    }


    private Task<?> task = null;
//    private static Consumer<Stage> springStartMain;

    public ApplicationController() {
        this.task = task;
        /*叉掉窗口后仍运行 参数为 false*/
        Platform.setImplicitExit(false);
    }


    /*生命周期——初始化——只有一次*/
    /*一定不要进入其他线程*/
    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {
        /*检查当前磁盘容量*/
//        disk_check.setText(new String(new DiskSpaceUtil().testDisk(IniDTO.getSftp_path())));
//        /*机床状态*/
//        listen_info.setText(String.valueOf(CncDTO.getCncWorkState()));
//        /*监听默认开启*/
//        listenCNC.setSelected(true);
//        /*opcuaserver默认开启*/
//        opc_button.setSelected(true);
//        /*sftp默认开启*/
//        sftp_button.setSelected(true);
//        /*机床IP地址*/
        api_url.setText("http://"+IniDTO.getSftp_host()+":"+IniDTO.getHttpPort()+"/cncData");
        cnc_net_ip.setText(CncDTO.getCnc_ip());
//        /*机床端口*/
        cnc_net_port.setText(CncDTO.getCnc_port());
//        /*opc服务地址*/
        opc_server_uri.setText(IniDTO.getOpcua_server_url());
//        /*sftp*/
//        sftp_server_uri.setText(IniDTO.getSftp_host());
        shou_quan.setText(IniDTO.getShouquan());
//        sftp_server_user.setText(IniDTO.getSftp_username());
//        sftp_server_pwd.setText(IniDTO.getSftp_password());
//        sftp_server_path.setText(IniDTO.getSftp_path());
//        sftp_server_port.setText(IniDTO.getSftp_port());
    }
    

    /**
     * 退出
     *
     * @param actionEvent
     */
    public void do_exit(ActionEvent actionEvent) {

        Platform.runLater(() -> System.exit(1));
    }

    /*------------------------------------------------------------*/
    @FXML
    private StackPane statusPlace;
    private ImageView runImage = new ImageView(IconStorage.STATUS_RUNNING.getIcon());
    private ImageView errorImage = new ImageView(IconStorage.STATUS_ERROR.getIcon());

    public void a() {

        Platform.runLater(new Runnable() {
            public void run() {
//                service4.cancel();
//                service4.restart();
                try {
                    if (new CheckCNCImpl().checkCNCOnline(cnc_net_ip.getText(), Integer.parseInt(cnc_net_port.getText()))) {
                        statusPlace.getChildren().remove(runImage);
                        statusPlace.getChildren().remove(errorImage);
                        statusPlace.getChildren().add(runImage);
//                cnc_net_state.setText("机床在线");
                        doNotify("提示", "可以联通", "dialog-information.png");
                    } else {
                        statusPlace.getChildren().remove(runImage);
                        statusPlace.getChildren().remove(errorImage);
                        statusPlace.getChildren().add(errorImage);
//                cnc_net_state.setText("机床不在线");
                        doNotify("提示", "无法联通", "dialog-information.png");
                    }

//            if (cnc_net_state.getText() == "" || cnc_net_ip.getText() == "" || cnc_net_port.getText() == "") {
//                statusPlace.getChildren().remove(runImage);
//                statusPlace.getChildren().remove(errorImage);
//                statusPlace.getChildren().add(errorImage);
//                cnc_net_state.setText("请填信息");
//
//            }
                } catch (Throwable throwable) {
                    log.error("通信异常" + throwable);
                }


            }

        });

    }


    /**
     * 每隔一段时间 5秒 刷新一下 整体UI页面相关信息
     */

//    @Scheduled(fixedRate = 500)
//    public void workTimeListener() {
//        Platform.runLater(new Runnable() {
//
//            public void run() {
//
//                /*联通性测试*/
////                a();
//
////
////                /*机床状态*/
////                listen_info.setText(String.valueOf(CncDTO.getCncWorkState()));
////
////
////                /*工件数*/
////                num_count.setText(String.valueOf(CountDTO.getTodayCount()));
//
//
//
////                /*SFTP配置信息监听*/
////                sftp_server_uri.setText(IniDTO.getSftp_host());
////                sftp_server_user.setText(IniDTO.getSftp_username());
////                sftp_server_pwd.setText(IniDTO.getSftp_password());
////                sftp_server_path.setText(IniDTO.getSftp_path());
//
//
//
//            }
//
//        });

//    }


//
//
//    /*--------------------------------------------------------------------------------------*/

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        //设定一个长度20的定时任务线程池
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(1));
    }




    /*------------------------------SFTP------------------------------------*/

    Service<Void> service_sftp = new Service<Void>() {
        @SneakyThrows
        @Override
        protected Task<Void> createTask() {

            System.out.println("启动SFTP服务");
            //启动服务
            try {
                IniDTO.setSftp_username(sftp_server_user.getText());
                IniDTO.setSftp_password(sftp_server_pwd.getText());
                IniDTO.setSftp_host(sftp_server_uri.getText());
                IniDTO.setSftp_path(sftp_server_path.getText());
                IniDTO.setSftp_port(sftp_server_port.getText());

//                IniDTO.setSftp_port(sftp.getText());

                String sftp_username = sftp_server_user.getText();
                String sftp_password = sftp_server_pwd.getText();
                String sftp_host = sftp_server_uri.getText();
                String sftp_path = sftp_server_path.getText();
                String sftp_port = sftp_server_port.getText();

                IniWriter.setProfileString(/*path*/Check_Info.NATIVE_LIBRARY_NAME,
                        "config",
                        "--sftp.username",
                        sftp_server_user.getText());

                IniWriter.setProfileString(/*path*/Check_Info.NATIVE_LIBRARY_NAME,
                        "config",
                        "--sftp.password",
                        sftp_server_pwd.getText());

                IniWriter.setProfileString(/*path*/Check_Info.NATIVE_LIBRARY_NAME,
                        "config",
                        "--sftp.port",
                        sftp_server_port.getText());

                IniWriter.setProfileString(/*path*/Check_Info.NATIVE_LIBRARY_NAME,
                        "config",
                        "--sftp.path",
                        sftp_server_path.getText());

                IniWriter.setProfileString(/*path*/Check_Info.NATIVE_LIBRARY_NAME,
                        "config",
                        "--sftp.host",
                        sftp_server_uri.getText());


//                        //检查端口占用
                new TestService(sftp_port);
//                        testPort(port_Info.getText());
                RunServer.serverBean = SftpServerUtils.setupSftpServer(sftp_username, sftp_password, sftp_host, Integer.parseInt(sftp_port), sftp_path);

            } catch (Throwable throwable) {
                //启动中断
                log.error("重新启动失败2{}", throwable);
            }


            return new Task<Void>() {

                @Override
                protected Void call() {
                    doNotify("提示", "启动SFTP服务", "dialog-information.png");
                    return null;
                }
            };
        }
    };

    @SneakyThrows
    public void sftp_starter(ActionEvent actionEvent) {
        if (sftp_button.isSelected()) {
            Platform.runLater(new Runnable() {
                public void run() {
                    service_sftp.cancel();
                    service_sftp.restart();
                }
            });
        } else {
            //关闭服务
            SftpServerUtils.stopServer(RunServer.serverBean);
            doNotify("提示", "关闭SFTP服务", "dialog-information.png");
        }

    }

    public void opc_starter(ActionEvent actionEvent) {
    }


    @Override
    public void accept(Stage stage) {

    }

    @Override
    public Consumer<Stage> andThen(Consumer<? super Stage> after) {
        return null;
    }


    public void do_btn_count(ActionEvent actionEvent) {
    }

    public void listenCNC_btn(ActionEvent actionEvent) {
    }

    public void sftp_info(ActionEvent actionEvent) {
    }

    public void ac_run_with_sys(ActionEvent actionEvent) {
    }
}
